package com.desktop.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.Comparator;

/**
 * @author 粥灰灰
 * @created 2022/2/3
 * @version 1.0
 * @Description 处理文件的工具类
 */
public class MyFileUtil {
    /**
     * 测试方法
     * @param args
     */
    public static void main(String[] args) {
        String resourceFolder = "src/resource/elaina/";
        //renameTo(resourceFolder);
    }

    /**
     * 将帧图片从0开始按顺序重命名，方便程序使用
     * @param resourceFolder 要修改的图片所在文件夹
     */
    public static void renameTo(String resourceFolder) {
        File folder = new File(resourceFolder);
        File[] files = folder.listFiles();
        sortFile(files);
        int i = 0;
        for (File temp : files) {
            temp.renameTo(new File(resourceFolder + i + ".png"));
            i++;
        }
    }

    /**
     * 根据文件创建时间进行排序
     * @param files
     */
    public static void sortFile(File[] files)
    {
        if (null != files && files.length > 0) {
            Arrays.sort(files, new Comparator<File>() {
                @Override
                public int compare(File o1, File o2) {
                    Long o1Create = getFileCreateTime(o1.getAbsolutePath());
                    Long o2Create = getFileCreateTime(o2.getAbsolutePath());
                    return o1Create.compareTo(o2Create);
                }
            });
        }
    }

    public static int imagesCount(String folderName) {
        String resourceFolder = "src/resource/" + folderName;
        File folder = new File(resourceFolder);
        if (folder.isFile() || !folder.exists())
            return 0;
        return folder.listFiles().length;
    }

    /**
     * 获取文件创建时间
     * @param fileAbsolutePath
     * @return
     */
    public static Long getFileCreateTime(String fileAbsolutePath) {
        File file = null;
        try {
            file = new File(fileAbsolutePath);
            Path path = Paths.get(fileAbsolutePath);
            BasicFileAttributeView bv = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
            BasicFileAttributes ba = bv.readAttributes();
            return ba.creationTime().toMillis();
        } catch (IOException e) {
            e.printStackTrace();
            return file.lastModified();
        }

    }
}
